<?php
namespace Modules\Taxonomy\Controllers;

use Core\Mvc\Controller;
use Core\Paginator\Adapter\Collection as CollectionPaginator;
use Modules\Taxonomy\Library\Form;
use MongoDB\BSON\ObjectID;

class AdminController extends Controller
{
    public function indexAction($contentModel, $page)
    {
        $content = [];
        $query = [
            'conditions' => [
                'contentModel' => $contentModel,
                'parent' => 0
            ],
            'sort' => [
                'weight' => 1,
                'changed' => -1,
            ],
            'limit' => 10,
            'skip' => 10 * ($page - 1)
        ];
        $entityList = $this->config->cache('entity');
        $entityInfo = $entityList['term'];
        $entity = $this->entityManager->get('term');
        $contentModelList = $this->entityManager->contentModel('term');
        if (!isset($contentModelList[$contentModel])) {
            return $this->notFount();
        }
        $entityAddForm = $entity->setContentModel($contentModel)->setField()->addForm();
        if ($entityAddForm->hasSubmit()) {
            if ($entity->getSaveState() === true) {
                $this->flash->success('新增词汇成功');
            } elseif ($entity->getSaveState() === false) {
                $this->flash->error('新增词汇失败');
            }
        }
        /*
         * proccess filter form
         */
        if (isset($entityInfo['filterForm'])) {
            $filterInfo = $this->config->get($entityInfo['filterForm']);
            $filterInfo['_options'] += [
                '_entity' => $entity,
                '_page' => $page,
                '_query' => $query,
            ];
            $filterForm = $this->form->create($filterInfo);
            if ($filterForm->isValid()) {
                $filterSave = $filterForm->save();
                if (!$filterSave !== false) {
                    $query = $filterSave;
                }
            }
        }
        /*
         * end process filter form
         */

        $data = $entity->find($query);
        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => $entityInfo['class']
        ]);
        $contentModelInfo = $contentModelList[$contentModel];
        $content['filter'] = array(
            '#templates' => 'box',
            'max' => false,
            'color' => 'widget',
            'hiddenTitle' => false,
            'size' => '12',
            'wrapper' => true,
            'content' => array(
                'filterForm' => $filterForm->renderForm(),
            ),
        );

        if ($this->request->isPost() && $this->request->hasPost('rh')) {
            $rh = json_decode($this->request->getPost('rh'));
            $rh = jsonToHierarchy($rh);
            Form::saveTermSort($rh);
            $this->flash->success('菜单排序成功');
        }

        self::$variables += array(
            'type' => $contentModel,
            'typeInfo' => $contentModelInfo,
            '#templates' => 'page',
            'title' => '术语词汇',
            'description' => $contentModelInfo['name'] . '列表',
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '列表',
                ),
            ),
            'content' => &$content,
        );
        // 添加编辑菜单
        $content['termList'] = array(
            '#templates' => 'box',
            'title' => $contentModelInfo['name'] . '列表',
            'max' => false,
            'wrapper' => true,
            'color' => 'primary',
            'size' => '6',
            'content' => array(
                '#templates' => 'adminTermList',
                'id' => 'menuLinkHierarchy',
                'title_display' => false,
                'data' => $dataPagination->getPaginate(),
            ),
        );
        $content['termHandle'] = array(
            '#templates' => 'box',
            'title' => '添加' . $contentModelInfo['name'],
            'max' => false,
            'id' => 'right_handle',
            'wrapper' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(
                'termForm' => $entityAddForm->renderForm(),
            ),
        );
    }

    public function editorAction($id)
    {
        $term = $this->entityManager->get('term', [
            'conditions' => [
                '_id' => new ObjectID($id)
            ]
        ]);
        if (!$term) {
            throw new \Exception('术语词汇不存在');
        } else {
            $termEditorForm = $term->editForm();
            if ($termEditorForm->hasSubmit()) {
                if ($term->getSaveState() === true) {
                    $this->flashSession->success('保持成功');
                } elseif ($term->getSaveState() === false) {
                    $this->flashSession->error('保持失败');
                }
                return $this->moved(array('for' => 'adminTermList', 'contentModel' => $term->contentModel, 'page' => 1));
            }
        }
        self::$variables += array(
            '#templates' => 'pageNoWrapper',
            'content' => array(
                'termEditorForm' => array(
                    '#templates' => 'box',
                    'wrapper' => false,
                    'title' => '词汇编辑-' . $term->name,
                    'max' => false,
                    'color' => 'success',
                    'size' => '12',
                    'content' => array(
                        'termEditorForm' => $termEditorForm->renderForm(),
                    ),
                ),
            ),
        );
    }

    public function deleteAction($id)
    {
        //获取下属term并更新
        $term = $this->entityManager->get('term', [
            'conditions' => [
                '_id' => new ObjectID($id)
            ]
        ]);
        if (!$term) {
            $this->flashSession->error('数据不存在：' . $id);
        } else {
            if ($term->delete()) {
                $this->flashSession->success('删除成功');
            } else {
                $this->flashSession->error('删除失败');
            }
        }
        $this->view->disable();
        return $this->temMoved(array(
            'for' => 'adminTermList',
            'contentModel' => $term->contentModel,
            'page' => 1,
        ));
    }
}
